import { useEffect, useRef } from "react";
import "./VideoPlayer.css";

export default function VideoPlayer({
  posterURL,
  videoURL,
  captionURL,
  timeStamp,
  setTimeStamp,
}) {
  const videoRef = useRef();
  // useEffect(() => {
  //   /// in case the videoURL is empty
  //   if (videoURL.length === 0) return;
  //   const mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
  //   if (videoRef.current && MediaSource.isTypeSupported(mimeCodec)) {
  //     const mediaSource = new MediaSource();
  //     const urlOfMediaSource = URL.createObjectURL(mediaSource);
  //     videoRef.current.src = urlOfMediaSource;
  //     mediaSource.addEventListener("sourceopen", () => {
  //       const sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
  //       sourceBuffer.addEventListener("error", console.log);
  //       fetch(videoURL)
  //         .then(function (response) {
  //           return response.arrayBuffer();
  //         })
  //         .then(function (sourceData) {
  //           sourceBuffer.appendBuffer(sourceData);
  //         });
  //     });
  //   }
  // }, [videoRef, videoURL]);
  useEffect(() => {
    if (videoRef.current) {
      const timeStampInterval = setInterval(() => {
        setTimeStamp(videoRef.current.currentTime);
      }, 2000);
      return () => clearInterval(timeStampInterval);
    }
  }, [videoRef, setTimeStamp]);

  return (
    <>
      <video
        ref={videoRef}
        id="player"
        controls
        playsInline
        poster={posterURL}
        src={videoURL}
      >
        <track
          kind="captions"
          label="中文"
          srcLang="zh"
          src={captionURL}
          default
        />
      </video>
    </>
  );
}
